<?php

namespace common\models\cms;

use Yii;
use common\helpers\Url;
use common\models\user\UserFavorite;
use common\models\site\Map;
use common\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%cms_article}}".
 *
 * @property int $id
 * @property int $channel_id 频道ID
 * @property string $title 标题
 * @property string $format 文章格式：default普通文章，gallery图集，video视频
 * @property string|null $thumb 封面图
 * @property string|null $keywords 关键词
 * @property string|null $description 导读简介
 * @property string|null $date 纪事日期
 * @property string|null $url 外链地址
 * @property int $duration 视频时长
 * @property int $picture_nums 组图数量
 * @property int $allow_comment 允许评论，0禁止，1开启
 * @property string|null $author 撰稿人
 * @property int $author_id 撰稿人ID
 * @property int $top_at 置顶时间
 * @property int $recommend_id 推荐ID
 * @property int $publish_at 发表时间
 * @property int $status 状态
 * @property int $created_at
 * @property int $updated_at
 * @property int $deleted_at
 */
class CmsArticle extends \common\db\ActiveRecord {

    /**
     * 文章状态
     */
    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;

    /**
     * 是否开启评论
     */
    const ALLOW_COMMENT_YES = 1;
    const ALLOW_COMMENT_NO = 0;

    /**
     * 文章格式
     */
    const FORMAT_DEFAULT = 'default';
    const FORMAT_GALLERY = 'gallery';
    const FORMAT_VIDEO = 'video';
    const FORMAT_AUDIO = 'audio';
    const FORMAT_CALENDAR = 'calendar';

    /**
     * 文章格式
     * 无图
     */
    const TEMPLATE_TEXT = 'text';
    const TEMPLATE_THUMB = 'thumb';
    const TEMPLATE_BANNER = 'banner';
    const TEMPLATE_GRID = 'grid';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%cms_article}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['channel_id', 'duration', 'picture_nums', 'allow_comment', 'author_id', 'top_at', 'recommend_id', 'publish_at', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['title'], 'required'],
            [['format'], 'string'],
            [['date'], 'safe'],
            [['title'], 'string', 'max' => 80],
            [['thumb', 'keywords', 'description', 'url'], 'string', 'max' => 255],
            [['author'], 'string', 'max' => 20],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'channel_id' => '频道ID',
            'title' => '标题',
            'format' => '内容形式',
            'thumb' => '封面图',
            'keywords' => '关键词',
            'description' => '导读简介',
            'date' => '纪事日期',
            'url' => '外链地址',
            'duration' => '视频时长',
            'picture_nums' => '组图数量',
            'allow_comment' => '允许评论',
            'author' => '撰稿人',
            'author_id' => '撰稿人ID',
            'top_at' => '置顶时间',
            'recommend_id' => '推荐ID',
            'publish_at' => '发表时间',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    /**
     * 关联文章详情
     */
    public function getAdminer() {
        return $this->hasOne(\common\models\AdminUser::class, ['id' => 'author_id']);
    }

    /**
     * 关联文章详情
     */
    public function getChannel() {
        return $this->hasOne(CmsChannel::class, ['id' => 'channel_id']);
    }

    /**
     * 关联详情
     */
    public function getData() {
        return $this->hasOne(CmsArticleDefault::class, ['article_id' => 'id']);
    }

    /**
     * 关联大事记
     */
    public function getCalendar() {
        return $this->hasOne(CmsArticleCalendar::class, ['article_id' => 'id']);
    }

    /**
     * 关联图集
     */
    public function getAlbum() {
        return $this->hasMany(CmsArticleGallery::class, ['article_id' => 'id']);
    }

    /**
     * 关联视频
     */
    public function getVideo() {
        return $this->hasOne(CmsArticleVideo::class, ['article_id' => 'id']);
    }

    /**
     * 关联音频
     */
    public function getAudios() {
        return $this->hasMany(CmsArticleAudio::class, ['article_id' => 'id']);
    }

    /**
     * 关联音频
     */
    public function getStats() {
        return $this->hasOne(CmsArticleStats::class, ['article_id' => 'id']);
    }

    /**
     * 关联音频数目
     */
    public function getAudioCount() {
        return $this->getAudios()->count();
    }

    /**
     * 获取缩略图
     */
    public function getBody() {
        if ($this->data) {
            return $this->data->body;
        }
        return '';
    }

    /**
     * 获取缩略图
     */
    public function getThumbUrl() {
        return Url::attach($this->thumb);
    }

    /**
     * 获取章图集
     */
    public function getPictures() {
        $album = $this->album;
        $pictures = [];
        if ($album) {
            foreach ($album as $picture) {
                $pictures[$picture->id] = $picture->source;
            }
        }
        return array_values($pictures);
    }

    /**
     * 获取围栏地址
     */
    public function getMapId() {
        $query = Map::find()->andWhere(['from' => 'CmsArticle' . ucfirst($this->format)]);
        $map = $query->one();
        if ($map) {
            return $map->id;
        }
        return 0;
    }

    public function getAuthorText() {
        if ($this->author) {
            return $this->author;
        }
        return $this->adminer ? $this->adminer->username : '北看台青年';
    }

    public function getFrom() {
        $time = $this->publishTime;
        if ($this->channel) {
            return [
                'icon' => $this->channel->icon,
                'text' => $this->channel->name,
                'time' => $time,
            ];
        }
        $icon = $this->adminer ? $this->adminer->portrait : '';
        if (!$icon) {
            $icon = '/assets/logo.png';
        }
        return [
            'icon' => Url::attach($icon),
            'text' => $this->authorText,
            'time' => $time,
        ];
    }

    public function getCollects() {
        return $this->hasMany(UserFavorite::className(), ['model_id' => 'id'])->andWhere([
            'model' => UserFavorite::MODEL_ARTICLE,
        ]);
    }

    public function getCollected() {
        return false;
    }

    /**
     * 检测获取用户是否点赞过
     */
    public function getLiked() {
        if (Yii::$app->user->isGuest) {
            return false;
        }
        return $this->hasOne(CmsArticleLike::className(), ['article_id' => 'id'])->andWhere([
            'comment_id' => 0,
            'user_id' => Yii::$app->user->id
        ])->exists();
    }

    public function getTags() {
        if ($this->keywords && trim($this->keywords)) {
            return explode(' ', $this->keywords);
        }
        if (!empty($this->channels)) {
            return ArrayHelper::getColumn($this->channels, 'name');
        }
        return [];
    }

    public function getTagText() {
        $tags = $this->tags;
        return array_shift($tags);
    }

    public function getPreviewUrl() {
        $route = [
            'preview'
        ];
        $route[] = 'article';
        $route[] = $this->id;
        return Url::h5(implode('/', $route));
    }

    public function getMplink() {
        $format = $this->format;
        if ($format == 'default') {
            $format = 'index';
        }
        return Url::mplink('/pages/article/' . $format . '/main', [
            'id' => $this->id
        ]);
    }

    public function getPublishTime() {
        $value = $this->publish_at ?: $this->created_at;
        if ($value > time() - 86400 * 30) {
            return date('m-d H:i', $value);
        } elseif ($value > time() - 86400 * 30 * 3) {
            return date('Y-m-d', $value);
        }
        return Yii::$app->formatter->asRelativeTime($value);
    }

    /**
     * 是否可以发表
     */
    public function canPublish() {
        if ($this->format == static::FORMAT_AUDIO && !$this->audioCount) {
            return false;
        }
        if ($this->status == static::STATUS_DEFAULT && !$this->deleted_at) {
            return true;
        }
        return false;
    }

}
